<template>
    <div>
        <el-row :gutter="20">
            <!-- 左侧 -->
            <el-col :span="statement.status == 0 ? 15 : 22" :offset="1" class="box-left">
                <!-- 左上结算单部分（结算单详情） -->
                <el-row class="box-left-top">
                    <el-col :span="24">
                        <el-descriptions :column="2">
                            <el-descriptions-item label="客户姓名">{{ statement.customerName }}</el-descriptions-item>
                            <el-descriptions-item label="联系方式">{{ statement.customerPhone }}</el-descriptions-item>
                            <el-descriptions-item label="车牌号码">{{ statement.licensePlate }}</el-descriptions-item>
                            <el-descriptions-item label="汽车类型">{{ statement.carSeries }}</el-descriptions-item>
                            <el-descriptions-item label="服务类型">
                                <dict-tag :options="dict.type.appoint_serv_type" :value="statement.serviceType"/>
                            </el-descriptions-item>
                            <el-descriptions-item label="到店时间">{{ statement.actualArrivalTime }}</el-descriptions-item>
                            <el-descriptions-item label="总消费金额">{{ totalSum }}</el-descriptions-item>
                            <el-descriptions-item label="实付金额">{{ totalSum - statement.discountAmount >= 0 ? 
                            totalSum - statement.discountAmount : 0 }}</el-descriptions-item>
                            <el-descriptions-item label="优惠价格" v-if="statement.status == 0">
                                <el-input v-model="statement.discountAmount" @change="changeDiscountAmount"></el-input>
                            </el-descriptions-item>
                            <el-descriptions-item v-if="statement.status == 1" label="优惠价格">{{ statement.discountAmount }}</el-descriptions-item>
                        </el-descriptions>
                </el-col>
                </el-row>
                <!-- 左下结算单明细部分（结算单明细列表） -->
                <el-row class="box-left-bottom">
                    <el-col :span="24">
                        <el-button
                            type="primary"
                            plain
                            icon="el-icon-plus"
                            size="mini"
                            @click="itemSaveOp"
                            :disabled="saveBtn"
                            v-if="statement.status == 0"
                        >保存</el-button>
                        <el-button
                            type="warning"
                            plain
                            icon="el-icon-plus"
                            size="mini"
                            :disabled="payBtn"
                            @click="payOp"
                            v-if="statement.status == 0"
                        >支付</el-button>
                        <right-toolbar v-if="statement.status == 0" :showSearch.sync="showSearch" @queryTable="getstatementItemListOp"></right-toolbar>
                        <el-table
                          :data="statementItemList"
                          style="width: 100%;margin: 1% 0;">
                          <el-table-column
                            prop="itemName"
                            label="服务名称"
                            >
                          </el-table-column>
                          <el-table-column
                            prop="itemPrice"
                            label="服务价格"
                            >
                          </el-table-column>
                          <el-table-column
                            prop="itemQuantity"
                            label="数量">
                          </el-table-column>
                          <el-table-column label="操作" v-if="statement.status == 0">
                            <template slot-scope="scope">
                                <el-button size="small" icon="el-icon-plus" type="primary" @click="statementItemPlus(scope.$index)"></el-button>
                            <el-button size="small" icon="el-icon-minus" type="danger" @click="statementItemMinus(scope.$index)"></el-button>
                            </template>
                          </el-table-column>
                        </el-table>
                        <div class="page">
                          显示第 1 到第 {{ statementItemList.length }} 条记录，总共
                          {{ statementItemList.length }} 条记录
                        </div>
                    </el-col>
                </el-row>
            </el-col>
            <!-- 右侧 -->
            <el-col :span="8" class="box-right" v-if="statement.status == 0">
                <!-- 右上高级搜索部分 -->
                <el-row>
                    <el-col :span="24" class="search_box">
                        <!-- 高级搜索 -->
                        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
                          <el-form-item label="服务名称" prop="name">
                            <el-input
                              v-model="queryParams.name"
                              placeholder="请输入服务项名称"
                              clearable
                              @keyup.enter.native="handleQuery"
                            />
                          </el-form-item>
                          <el-form-item label="是否套餐" prop="carPackage">
                            <el-select v-model="queryParams.carPackage" placeholder="请选择是否套餐" clearable>
                              <el-option
                                v-for="dict in dict.type.item_serv_package"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                              />
                            </el-select>
                          </el-form-item>
                          <el-form-item label="服务分类" prop="serviceCatalog">
                            <el-select v-model="queryParams.serviceCatalog" placeholder="请选择服务分类" clearable>
                              <el-option
                                v-for="dict in dict.type.item_serv_type"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                              />
                            </el-select>
                          </el-form-item>
                          <el-form-item label=" ">
                            <el-button type="success" icon="el-icon-search" size="medium" round @click="handleQuery">搜索</el-button>
                          </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
                <!-- 右下已上架服务项部分（服务项列表）-->
                <el-row class="box-right-bottom">
                    <el-col :span="24" class="serviceItem_box">
                        <el-table :data="serviceItemList">
                            <el-table-column label="服务项名称" align="center" prop="name" />
                            <el-table-column label="服务项折扣价" align="center" prop="discountPrice" />
                            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button
                                    size="small"
                                    icon="el-icon-plus"
                                    type="primary"
                                    @click="serviceItemPlus(scope.row)"
                                ></el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="page">
                            显示第 1 到第 {{ serviceItemList.length }} 条记录，总共
                            {{ serviceItemList.length }} 条记录
                        </div>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>
    </div>
</template>
<style>
    .box-left,.box-right{
        margin-top: 2%;
    }
    .box-left .el-col{
        padding:2%;
    }
    .box-left-bottom{
        margin-top:1%;
    }
    .box-left-bottom,.box-left-top{
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    }
    .el-input {
      max-width: 217px;
    }
    .search_box{
        width:98%;
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
        padding:1% 3%;
    }
    .serviceItem_box{
        width:98%;
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
        padding:3% 3%;
    }
    .box-right-bottom{
        margin-top:2%;
    }
    .page {
        line-height: 34px;
        font-size: 13px;
        color: #676a6c;
    }
</style>
<script>
import { getServiceItemList } from "@/api/business/serviceItem";
import { getStatement } from "@/api/business/statement";
import { itemSave,getstatementItemList,pay } from "@/api/business/statementItem";

export default {
    dicts: ['item_serv_package','item_serv_type','appoint_serv_type'],
    data(){
        return{
            statementItemList:[],   // 结算单明细列表
            serviceItemList:[],     // 已上架服务项明细列表
            statement:{             // 结算单对象
                // totalAmount:0,
                discountAmount:0,
            },           
            statementId:this.$route.params.statementId, // 结算单id
            // 显示搜索条件
            showSearch: true,
            // 保存按钮是否禁用
            saveBtn:true,
            // 支付按钮是否禁用
            payBtn:true,
            // 高级搜索条件
            queryParams:{
                name:null,
                carPackage:null,
                serviceCatalog:null,
                saleStatus:1,       // 写死，只要已上架的。
            }
        }
    },
    created(){
        // 初始化数据方法
        this.initDate();
    },
    methods:{
        // 初始化数据方法
        initDate(){
            // 加载已上架服务项列表数据.
            this.getServiceItemListOp();
            // 加载结算单数据
            this.getStatementByIdOp();
            // 加载结算单明细数据
            this.getstatementItemListOp();
        },
        // 加载已上架服务项列表数据.
        getServiceItemListOp(){
            getServiceItemList(this.queryParams).then(response => {
              this.serviceItemList = response.data;
            });
        },
        // 加载结算单数据
        getStatementByIdOp(){
            getStatement(this.statementId).then(resp => {
                this.statement = resp.data;
            })
        },
        // 加载结算单明细列表
        getstatementItemListOp(){
            getstatementItemList(this.statementId).then(resp=>{
                this.statementItemList = resp.data;
                if(this.statementItemList.length > 0){
                    this.payBtn = false;
                }
            })
        },
        // 高级搜索部分的搜索按钮
        handleQuery(){
            this.getServiceItemListOp();
        },
        // 右侧已上架服务项部分+号按钮
        serviceItemPlus(row){
            // 根据传入的 itemId，来寻找当前结算单明细列表中是否存在对应 itemId 相同的数据。
            let index = this.getStatementItemIndexByServiceItemId(row.id);
            if(index > -1){
                // 若存在则数量 + 1
                this.statementItemList[index].itemQuantity++;
            } else {
                // 若不存在则插入新数据
                this.statementItemList.push(this.createStatementItem(row));
            }    
            this.saveBtn = false;
            this.payBtn = true;
        },
        // 封装结算单明细对象
        createStatementItem(row){
            let obj = {
                itemName:row.name,
                itemPrice:row.discountPrice,
                itemQuantity:1,
                itemId:row.id,
                statementId:this.statementId,
            };
            return obj;
        },
        // 判断传入的 id 再结算单明细列表中是否存在相同的 itemId
        getStatementItemIndexByServiceItemId(id){
            let idx = -1;
            if(this.statementItemList.length < 1){
                return idx;
            }
            this.statementItemList.forEach((element,index) => {
                if(element.itemId == id){
                    // 找到了。返回对应的索引
                    // console.log("满足条件的索引=>index:" + index)
                    idx = index;
                    return;
                }
            })
            return idx;
        },
        // 点击左下结算单明细加号
        statementItemPlus(index){
            this.statementItemList[index].itemQuantity++;
            this.saveBtn = false;
            this.payBtn = true;
        },
        // 点击左下结算单明细减号
        statementItemMinus(index){
            // 判断剩余数量
            if(this.statementItemList[index].itemQuantity == 1){
                // 若 == 1，点击 -, 执行删除该元素
                this.statementItemList.splice(index,1);
            } else {
                // 若 != 1，点击 -，数量-1
                this.statementItemList[index].itemQuantity--;
            }
            this.saveBtn = false;
            this.payBtn = true;
        },
        // 保存明细项
        itemSaveOp(){
            this.$modal.confirm("您确定要保存明细项吗？").then(()=>{
                // 封装参数
                let data = {
                    discountAmount:this.statement.discountAmount,
                    itemList:this.statementItemList,
                }
                // 调用方法来发送请求
                itemSave(data).then(()=>{
                    this.$modal.msgSuccess("保存明细项成功");
                    this.saveBtn = true;
                    this.payBtn = false;
                })
            })
        },
        // 支付功能（结算单支付功能）
        payOp(){
            this.$modal.confirm("您确定要支付该结算单吗？").then(()=>{
                // 封装参数
                let data = {
                    discountAmount:this.statement.discountAmount,
                    itemList:this.statementItemList,
                }
                // 调用方法来发送请求
                pay(data).then(()=>{
                    this.$modal.msgSuccess("支付成功");
                    //重新刷新结算单
                    this.saveBtn = true;
                    this.payBtn = true;
                    this.getStatementByIdOp();
                })
            })
        },
        // 优惠价格改变时
        changeDiscountAmount(){
            this.saveBtn = false;
            this.payBtn = true;
        }
    },
    computed:{
        totalSum(){
            let sum = 0;
            this.statementItemList.forEach(ele => {
                sum += ele.itemPrice * ele.itemQuantity;
            })
            return sum;
        }
    },
}
</script>